# -*- coding: utf-8 -*-
# Create your views here.

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, EmptyPage, InvalidPage
from google.appengine.api import memcache as cache

from utils import url_read
from BeautifulSoup import BeautifulSoup
import re
import os
import logging
import random
from main.settings import *
from main.utils import get_cover
from main.models import Series, Episode, Comment
from django.contrib.auth.models import User

from google.appengine.ext import db
from ragendja.dbutils import get_object, db_create, get_object_list

site_url = 'http://www.xiaoli.cc/'

categoryTable_obj = re.compile(r'<table\sclass="tb01"\sid="categoryTable">.+?</table>', flags= re.DOTALL)
hottest_series_obj = re.compile(r'<h4>热门电视剧</h4>\s+(<div\sclass="content">.+?</div>)', flags= re.DOTALL)
new_series_obj = re.compile(r'<h4>最新添加的电视剧</h4>\s+(<div\sclass="content">.+?</div>)', flags= re.DOTALL)
latest_videos_obj = re.compile(r'<h4>最近更新.+?</h4>\s+<div\sclass="content">\s+(<ul>.+?</ul>)', flags= re.DOTALL)

video_title_obj = re.compile(r'<h1>.+?</h1>', flags= re.DOTALL)
category_name_obj = re.compile(r'<a.+?>(.+?)</a>', flags= re.DOTALL)
series_name_obj = re.compile(r'(.+?)\([^\(\)]+?\)</h1>', flags= re.DOTALL)
category_id_obj = re.compile(r'<a\shref="/category/(.+?)">.+?</a>', flags= re.DOTALL)
seriesDes_obj = re.compile(r'<div\sid="seriesDes">.+?</div>', flags= re.DOTALL)
videos_obj = re.compile(r'<div\sid="videos">.+?</div>', flags= re.DOTALL)
video_image_obj = re.compile(r'div\sstyle="background:#fff;padding:10px;margin-bottom:10px;">\s+<img\ssrc="(.+?)"\s+style="display:block;width:190px;"\s+/>', flags= re.DOTALL)

video_title_h3_obj = re.compile(r'<h3>.+?</h3>', flags= re.DOTALL)
episodeInfo_obj = re.compile(r'<ul\sid="episodeInfo">.+?</ul>', flags= re.DOTALL)
subNav_obj = re.compile(r'<ul\sid="subNav"\sclass="clearfix">.+?</ul>', flags= re.DOTALL)
video_url_obj = re.compile(r'<a\shref="(http://[^"]+?)"\starget="_blank">宽屏版观看</a></p>', flags= re.DOTALL)
video_url_obj2 = re.compile(r'<a\shref="(http://[^"]+?)"\starget="_blank">立即观看</a></p>', flags= re.DOTALL)
episode_name_obj = re.compile(r'(.+?)</h3>', flags= re.DOTALL)


def index(request):
    return render_to_response('index.html',locals(), context_instance = RequestContext(request))

def category_i(request, category_id):
    height = category_high_map.get(int(category_id))
    return render_to_response('category_i.html',locals(), context_instance = RequestContext(request))

def category(request, category_id):
    url = site_url + 'category/%s' % category_id
    category_name = category_name_map.get(int(category_id))
    key = 'category-%s' % category_id
    cached_content = cache.get(key)
    if cached_content:
        logging.info('%s from cache' % key)
        categoryTable,hottest_series,new_series,latest_videos = cached_content
    else:
        logging.info('%s from remote' % key)
        content = url_read(url)
        categoryTable_m = categoryTable_obj.search(content)
        if categoryTable_m:
            categoryTable = categoryTable_m.group(0)
        else:
            categoryTable = ''
    
        hottest_series_m = hottest_series_obj.search(content)
        if hottest_series_m:
            hottest_series = hottest_series_m.group(1)
        else:
            hottest_series = ''
        
        new_series_m = new_series_obj.search(content)
        if new_series_m:
            new_series = new_series_m.group(1)
        else:
            new_series = ''
        
        latest_videos_m = latest_videos_obj.search(content)
        if latest_videos_m:
            latest_videos = latest_videos_m.group(1)
        else:
            latest_videos = ''
        cache.set(key, (categoryTable,hottest_series,new_series,latest_videos), CACHE_FETCHED_SECOND)
        
    return render_to_response('category.html',locals(), context_instance = RequestContext(request))

def detail(request, detail_id):
    url = site_url + 'video/detail/%s' % detail_id
    series = get_object(Series, 'xiaoli_series_id =', detail_id)
    if not series:
        series = db_create(Series, xiaoli_series_id=detail_id)
    
    key = 'detail-%s' % detail_id
    cached_content = cache.get(key)
    if cached_content:
        logging.info('%s from cache' % key)
        video_title,category_name,video_image,seriesDes,videos,hottest_series,new_series = cached_content
    else:
        logging.info('%s from remote' % key)
        content = url_read(url)
        video_title_m = video_title_obj.search(content)
        if video_title_m:
            video_title = video_title_m.group(0)
            category_name = category_name_obj.search(video_title).group(1)
            series_name = series_name_obj.search(video_title.split('|',2)[1]).group(1).strip()
            category_id = int(category_id_obj.search(video_title).group(1))
            video_image = get_cover(category_id,detail_id)
            series.xiaoli_category_id = str(category_id)
            series.name = series_name.decode('utf-8')
            series.save()
        else:
            video_title = ''
            
        seriesDes_m = seriesDes_obj.search(content)
        if seriesDes_m:
            seriesDes = seriesDes_m.group(0).replace('@www.xiaoli.cc','')
        else:
            seriesDes = ''
        
        videos_m = videos_obj.search(content)
        if videos_m:
            videos = videos_m.group(0)
        else:
            videos = ''
        
        hottest_series_m = hottest_series_obj.search(content)
        if hottest_series_m:
            hottest_series = hottest_series_m.group(1)
        else:
            hottest_series = ''
        
        new_series_m = new_series_obj.search(content)
        if new_series_m:
            new_series = new_series_m.group(1)
        else:
            new_series = ''
            
        cache.set(key, (video_title,category_name,video_image,seriesDes,videos,hottest_series,new_series), CACHE_FETCHED_SECOND)
    if request.user.is_authenticated():
        comments = get_object_list(Comment, 'series =', series, 'origin =', request.user.origin).order('-created')[:3]
    return render_to_response('detail.html',locals(), context_instance = RequestContext(request))

def detail_watch(request, detail_id, slug):
    url = site_url + 'video/detail/%s/%s' % (detail_id,slug)
    series = get_object(Series, 'xiaoli_series_id =', detail_id)
    if not series:
        series = db_create(Series, xiaoli_series_id=detail_id)
        
    episode = get_object(Episode, 'series =', series, 'xiaoli_slug =', slug)
    if not episode:
        episode = db_create(Episode, series = series, xiaoli_slug=slug)
        episode.xiaoli_category_id = episode.series.xiaoli_category_id
        episode.xiaoli_series_id = episode.series.xiaoli_series_id
        episode.series_name = episode.series.name
    user = request.user
    if user.is_authenticated():
        logging.info(u'%s watched %s' % (user,slug))
        episode.add_watched(user)
        episode.save()
        user.save()
        watched_user = episode.get_watched_user(user)
    key = 'detail_watch-%s' % slug
    cached_content = cache.get(key)
    if cached_content:
        logging.info('%s from cache' % key)
        video_title,episodeInfo,subNav,video_urls = cached_content
    else:
        logging.info('%s from remote' % key)
        content = url_read(url)
        video_title_m = video_title_h3_obj.search(content)
        if video_title_m:
            video_title = video_title_m.group(0)
            episode_name = episode_name_obj.search(video_title.rsplit('|',2)[1]).group(1).strip()
            
            episode.name = episode_name.decode('utf-8')
            episode.save()
        else:
            video_title = ''
        
        episodeInfo_m = episodeInfo_obj.search(content)
        if episodeInfo_m:
            episodeInfo = episodeInfo_m.group(0)
        else:
            episodeInfo = ''
        
        subNav_m = subNav_obj.search(content)
        if subNav_m:
            subNav = subNav_m.group(0)
        else:
            subNav = ''
        
        video_urls = video_url_obj.findall(content)
        if not video_urls:
            video_urls = video_url_obj2.findall(content)
        cache.set(key, (video_title,episodeInfo,subNav,video_urls), CACHE_FETCHED_SECOND)
        
    return render_to_response('detail_watch.html',locals(), context_instance = RequestContext(request))
 
def detail_watch_comment(request, detail_id, slug):
    series = get_object(Series, 'xiaoli_series_id =', detail_id)
    if not series:
        series = db_create(Series, xiaoli_series_id=detail_id)
        
    episode = get_object(Episode, 'series =', series, 'xiaoli_slug =', slug)
    if not episode:
        episode = db_create(Episode, series = series, xiaoli_slug=slug)
        episode.xiaoli_category_id = episode.series.xiaoli_category_id
        episode.xiaoli_series_id = episode.series.xiaoli_series_id
        episode.series_name = episode.series.name
        episode.save()
        
    user = request.user
    if request.method == 'POST' and user.is_authenticated():
        content = request.POST['content'].strip()
        if content:
            new_comment = db_create(Comment, user = user, content=content, series = series, episode = episode, origin = user.origin)
            return HttpResponseRedirect('?page=last')
        
    if user.is_authenticated():
        comments = get_object_list(Comment, 'episode =', episode, 'origin =', user.origin).order('created')
        if comments.count() == 0:
            comments = get_object_list(Comment, 'series =', series, 'origin =', user.origin).order('created')
    try:
        page = int(request.REQUEST.get('page', '1'))
    except ValueError:
        page = random.randint(-1000, 0)
    per_page = 5
    paginator = Paginator(comments, per_page)
    try:
        page_comments = paginator.page(page)
    except (EmptyPage, InvalidPage):
        page_comments = paginator.page(paginator.num_pages)
    return render_to_response('comment_i.html',locals(), context_instance = RequestContext(request))

def watched(request, category_id):
    user = request.user
    id_list = user.watched_series_ids
    logging.info(u"watched %s" % id_list)
    url = site_url + 'category/%s' % category_id
    category_name = category_name_map.get(int(category_id))
    key = 'category-%s' % category_id
    cached_content = cache.get(key)
    if cached_content:
        logging.info('%s from cache' % key)
        categoryTable,hottest_series,new_series,latest_videos = cached_content
    else:
        logging.info('%s from remote' % key)
        content = url_read(url)
        categoryTable_m = categoryTable_obj.search(content)
        if categoryTable_m:
            categoryTable = categoryTable_m.group(0)
        else:
            categoryTable = ''
    soup = BeautifulSoup(categoryTable)
    rows = soup.findAll('tr')[1:]
    for row in rows:
        detail_id = row.a['href'].split('/')[-1]
        if detail_id not in id_list:
            row.extract()
    categoryTable = unicode(soup)
    return render_to_response('watched.html',locals(), context_instance = RequestContext(request))

def help(request):
    return render_to_response('help.html',locals(), context_instance = RequestContext(request))
